package com.css.apps.base.log.action;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.css.apps.base.log.model.SLogClientinfo;
import com.css.apps.base.log.service.QueryLog;
import com.css.db.query.TransactionCache;
import com.css.webbase.webwork.action.AbstractAction;
import com.opensymphony.xwork.Action;

import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class LoginInfoOnMonthJob extends AbstractAction {

	private static Log log = LogFactory.getLog(LoginInfoOnMonthJob.class);

	@SuppressWarnings("unchecked")
	@Override
	public String go() {
		// 获取昨日时间
		TransactionCache tx = null;
		Calendar cal = Calendar.getInstance();
		Date createTime = cal.getTime();
		cal.add(Calendar.MONTH, -1);
		String lastMonth = new SimpleDateFormat("yyyy-MM").format(cal.getTime());

		// 查询统计浏览器信息
		String sql = "select a.opExplorer , count(a.opExplorer) from SLog a where to_char(a.opTime,'yyyy-MM') = :opTime and a.funcId = 'acl_user/login' group by a.opExplorer ";
		QueryLog qc = new QueryLog(sql);
		qc.setParameter("opTime", lastMonth);

		List<Object[]> rlst = qc.list();
		JSONObject json = new JSONObject();
		if (rlst != null) {
			for (Object[] objs : rlst) {
				if (objs[0] == null) {
					continue;
				} else {
					String type = objs[0].toString();
					String value = objs[1].toString();
					json.put(type, value);
				}
			}
		}
		SLogClientinfo clientinfo = new SLogClientinfo();
		clientinfo.setCountType("2");// 统计登录浏览器
		clientinfo.setLogType("2");// 按日统计
		clientinfo.setCountKey(lastMonth);
		clientinfo.setContent(json.toString());
		clientinfo.setCreateTime(createTime);

		// 查询统计系统信息
		String os_sql = "select a.opOs , count(a.opOs) from SLog a where to_char(a.opTime,'yyyy-MM') = :opTime and a.funcId = 'acl_user/login' group by a.opOs ";
		QueryLog os_qc = new QueryLog(os_sql);
		os_qc.setParameter("opTime", lastMonth);

		List<Object[]> os_rlst = os_qc.list();
		JSONObject os_json = new JSONObject();
		if (os_rlst != null) {
			for (Object[] objs : os_rlst) {
				if (objs[0] == null) {
					continue;
				} else {
					String type = objs[0].toString();
					String value = objs[1].toString();
					os_json.put(type, value);
				}

			}
		}
		SLogClientinfo os_clientinfo = new SLogClientinfo();
		os_clientinfo.setCountType("4");// 统计登录操作系统
		os_clientinfo.setLogType("2");// 按日统计
		os_clientinfo.setCountKey(lastMonth);
		os_clientinfo.setContent(os_json.toString());
		os_clientinfo.setCreateTime(createTime);

		try {
			tx = qc.getTransaction();
			tx.save(clientinfo);
			tx.save(os_clientinfo);
			tx.commit();
			return Action.SUCCESS;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			if (tx != null)
				tx.rollback();
			ex.printStackTrace();
			return Action.ERROR;
		}

	}

}
